package com.example.goodsserver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.goodsserver.entity.GoodsInfo;
import com.example.goodsserver.manager.GoodsManager;
import com.example.goodsserver.params.GoodsParams;
import com.example.goodsserver.params.PageGoodsParams;
import com.example.goodsserver.vo.GoodsInfoVO;
import com.example.userserver.enums.ReturnEnum;
import com.example.userserver.utils.BeanCopyUtils;
import com.example.userserver.vo.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService {
    @Autowired
    private GoodsManager goodsManager;
    public PageInfo<GoodsInfoVO> pageGoods(PageGoodsParams pageGoodsParams){
        if(StringUtils.isNotEmpty(pageGoodsParams.getOrderBy())){
            pageGoodsParams.setOrderBy("g."+pageGoodsParams.getOrderBy());
        }
        PageHelper.startPage(pageGoodsParams);
        List<GoodsInfoVO> list = goodsManager.listGoods(pageGoodsParams);
        PageInfo<GoodsInfoVO> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    public GoodsInfoVO getGoods(String id) {
        return goodsManager.getGoods(id);
    }

    public void deleteGoods(String id) {
        goodsManager.deleteGoods(id);
    }

    public void updateGoods(GoodsParams goodsParams) {
        GoodsInfo goodsInfo = goodsManager.getGoodsInfo(goodsParams.getId());
        BeanCopyUtils.copyPropertiesIgnoreNull(goodsParams, goodsInfo);
        goodsManager.updateGoods(goodsInfo);
        // 重置缓存
        goodsManager.selectDBSaveCache(goodsParams.getId());
    }

    public Result insertGoods(GoodsParams goodsParams) {
        GoodsInfo goodsInfo = new GoodsInfo();
        BeanCopyUtils.copyPropertiesIgnoreNull(goodsParams, goodsInfo);
        goodsManager.insertGoods(goodsInfo);
        return new Result(null, ReturnEnum.SUCCESS);
    }

    public PageInfo<GoodsInfoVO> pageGoodsPersonal(PageGoodsParams pageGoodsParams) {
        if(StringUtils.isNotEmpty(pageGoodsParams.getOrderBy())){
            pageGoodsParams.setOrderBy(pageGoodsParams.getOrderBy());
        }
        PageHelper.startPage(pageGoodsParams);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", pageGoodsParams.getUserId());
        if(StringUtils.isNotEmpty(pageGoodsParams.getTitle())){
            queryWrapper.like("title", pageGoodsParams.getTitle());
        }
        if(pageGoodsParams.getStatus() != 0){
            queryWrapper.eq("status", pageGoodsParams.getStatus());
        }
        List<GoodsInfoVO> list = goodsManager.pageGoodsPersonal(queryWrapper);
        PageInfo<GoodsInfoVO> pageInfo = new PageInfo(list);
        return pageInfo;
    }
}
